package com.forever.okhttpdemo.thread;

import java.io.IOException;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.forever.okhttpdemo.http.HttpUrl;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

public class PartPostFileAndLoginAsyncTask extends
		AsyncTask<String, Void, byte[]> {
	private Context context;

	public PartPostFileAndLoginAsyncTask(Context context) {
		this.context = context;

	}

	@Override
	protected byte[] doInBackground(String... params) {

		byte[] mbyte = null;

		try {
			OkHttpClient client = new OkHttpClient();
			// 上传数据类型
			MediaType mediaType = MediaType.parse("image/png");
			byte[] fileByte = HttpUrl.InputStreamToByteArray(context
					.getAssets().open("ic_launcher.png"));
			RequestBody fileBody = RequestBody.create(mediaType, fileByte);
			RequestBody formBody = new FormEncodingBuilder()
					.add("username", "wy").add("password", "123").build();

			MultipartBuilder multipartBuilder = new MultipartBuilder();

			multipartBuilder.addFormDataPart("username", "wy").addFormDataPart(
					"password", "123");
			RequestBody body = multipartBuilder.addPart(fileBody).build();

			Request request = new Request.Builder().url(params[0]).post(body)
					.build();
			Response response = client.newCall(request).execute();

			// 第二种方法

			if (response.isSuccessful()) {
				mbyte = response.body().bytes();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return mbyte;
	}

	@Override
	protected void onPostExecute(byte[] result) {
		super.onPostExecute(result);
		if (result != null) {

			Toast.makeText(context, new String(result), 0).show();
		} else {
			Toast.makeText(context, "失败", 0).show();
		}
	}

}
